import axios, { AxiosRequestConfig } from "axios";
import { Message } from "@arco-design/web-vue";
// 创建一个axios实例

const request = axios.create({
  baseURL: "http://localhost:8181",
  //超时时间 单位毫秒
  timeout: 10000,
  withCredentials: true,
});

//1. 请求拦截器 请求成功执行第一个，失败第二个
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token != null || token != undefined) {
      config.headers["token"] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//2. 响应拦截器
request.interceptors.response.use(
  (response) => {
    //未登录
    const { data } = response;
    if (data.code === 41000) {
      if (
        response.request.responseURL.includes("/user/get/login") &&
        window.location.pathname.includes("/user/login")
      ) {
        window.location.href = `/user/login?redirect=${window.location.href}`;
      }
    }
    return response;
  },
  (error) => {
    Message.error({
      content: error.message,
      duration: 1500,
    });

    // return Promise.reject(error)
    return;
  }
);

export default request;
